

export default {
    template: `<div class="show-time">
        {{year}}-{{month}}-{{day}}  {{hour}}:{{min}}:{{sec}}
    </div>`,

    // 此写法有误 => 组件复用时, 使用共有一个data选项
    // data:{
    //     // now: new Date("2024-1-1 00:00:00"),
    //     now: new Date(),
    //     timer: null,
    // },

    // 为保证组件复用时数据分离(让每一个组件都有其自己独立的数据), 在组件初始化阶段会调用data函数,将函数返回的对象作为挂载的数据
    data: function () {
        return {
            // now: new Date("2024-1-1 00:00:00"),
            now: new Date(),
            timer: null,
        }
    },
    methods: {
        update() {
            clearInterval(this.timer);
            this.timer = setInterval(() => {
                this.now = new Date();
            }, 1000)
        },
        stop() {
            clearInterval(this.timer);
        }
    },
    computed: {
        year() {
            return this.now.getFullYear();
        },
        month() {
            // 月份参数: 0 - 11 
            // 实际月份 = 月份参数 + 1
            var month = this.now.getMonth() + 1
            return month.toString().padStart(2, "0");
        },
        day() {
            var day = this.now.getDate()
            return day.toString().padStart(2, "0");
        },
        hour() {
            var hour = this.now.getHours();
            return hour.toString().padStart(2, "0");
        },
        min() {
            var min = this.now.getMinutes();
            return min.toString().padStart(2, "0");
        },
        sec() {
            var sec = this.now.getSeconds();
            return sec.toString().padStart(2, "0");
        },
        dateOption() {
            var year = this.now.getFullYear();
            var month = this.now.getMonth() + 1;
            var day = this.now.getDate();
            var hour = this.now.getHours();
            var min = this.now.getMinutes();
            var sec = this.now.getSeconds();
            return {
                year: year,
                month: month.toString().padStart(2, "0"),
                day: day.toString().padStart(2, "0"),
                hour: hour.toString().padStart(2, "0"),
                min: min.toString().padStart(2, "0"),
                sec: sec.toString().padStart(2, "0"),
            }
        }
    },
    mounted() {
        console.log(this);
        this.update();
    },
    beforeDestroy() {
        this.stop();
    }
}